﻿/*
 SharpContent
 Copyright (c) 2002-2009, State of Montana
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met:
 1. Redistributions of source code must retain the above copyright notice,
 this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 3. Neither the State of Montana nor the names of contributors may be used to endorse
 or promote products derived from this software without specific prior
 written permission.
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 DAMAGE.
 */
(function(){
	/*
	 * The relationship widget is meant to be used in panes.
	 * It relies on the modal widget for performing its duties, which are CRUDing relationships.
	 */
    var relationshipWidget = new Class({
        initialize: function(initialRelationships, deferredActions){
            /*
             * Initialize the widget table with a header...
             */
            this.browserClass = sharpRegistry.panes['browse.folder'];
            this.widgetReference = new Element('table', {
                id: 'relationshipTable'
            }).grab(new Element('thead').grab(this.makeHeaderRow())); // WTF: Get rid of widget reference. _this_ should be the reference.
            this.relationships = new Array();
			this.widgetReference.relationshipsAdded = new Array();
			this.widgetReference.relationshipsRemoved = new Array();
            if (initialRelationships && initialRelationships.length > 0) {
                initialRelationships.each(function(relationship){
                    this.add(relationship.getAttribute('type'), relationship.getAttribute('target'), this.relationships);
                }.bind(this));
            }
			this.deq = deferredActions;
            this.widgetReference.grab(new Element('tfoot').grab(this.makeInputRow()));
            return this.widgetReference;
        },
        add: function(type, location, rawStore){
            // TODO: Enforce no duplicate rows
            newRow = this.makeDataRow(type, location);
            if (rawStore) 
                rawStore.push({
                    'type': type,
                    'location': location
                });
            
			var relationshipXML = this.makeRelationshipXML(type, location);
			if (!this.widgetReference.relationshipsAdded.contains(relationshipXML)) {
				this.widgetReference.relationshipsAdded.push(relationshipXML);
				if (this.widgetReference.relationshipsRemoved.contains(relationshipXML)) {
					this.widgetReference.relationshipsRemoved.erase(relationshipXML);
				}
			}
			
            if (this.widgetReference) {
                var target = this.widgetReference.getElement('tbody');
                if (target) {
                    target.grab(newRow);
                }
                else {
                    this.widgetReference.grab(new Element('tbody').grab(newRow));
                }
            }
        },
        remove: function(type, location){
            this.relationships = this.relationships.filter(function(relationship){
                return relationship.location != location && relationship.type != type;
            });
			var relationshipXML = this.makeRelationshipXML(type, location);
			if (!this.widgetReference.relationshipsRemoved.contains(relationshipXML)) {
				this.widgetReference.relationshipsRemoved.push(relationshipXML);
				if (this.widgetReference.relationshipsAdded.contains(relationshipXML)) {
					this.widgetReference.relationshipsAdded.erase(relationshipXML);
				}
			}
        },
		makeRelationshipXML: function(type, location) {
			return '<mc:relation target="' + location + '" type="' + type + '"/>';
		},
		makeHeaderRow: function() {
			var type = 'Type',
				location = 'Location',
				row = new Element('tr', { 'id': type + location }),
				typeLabel = new Element('label', {
					'text': type,
					'for': 'type-input',
					'styles' : {
						'border-bottom': 'dotted 1px'
					}
				}),
				locationCell = new Element('th').grab(new Element('label', {
					'text': location,
					'for': 'location-input',
					'styles' : {
						'border-bottom': 'dotted 1px'
					}
				}));
			
			row.grab(new Element('th', { 'text': "This item's "}).grab(typeLabel));	
			row.grab(new Element('th',  {'text' : ' is ' }));
			row.grab(locationCell);
			row.grab(new Element('th'));
			row.grab(new Element('th'));
			return row;
		},
		makeDataRow: function(type, location) {
			var handle = type + "|" + location,
				row = new Element('tr', { 'id': handle }),
				locationCell = new Element('td'),
				deleteCell = new Element('td');
			
			locationCell.grab(new Element('a', {
				'href': location,
				'text': location.indexOf(sharpbar.applicationUrl) < 0 ? location : location.slice(sharpbar.applicationUrl.length)
			}));
			
			deleteCell.grab(new Element('input', {
                    'type': 'button',
                    'value': 'Delete',
                    'events': {
                        'click': function(){
                            var handleSegments = handle.split('|'),
								theRow = document.id(handle);
                            if (handleSegments || handleSegments.length == 2) 
                                this.remove(handleSegments[0], handleSegments[1]);
                            
                            if (theRow) 
                                theRow.destroy();
                        }.bind(this)
                    }
            }));
			
			row.grab(new Element('td', { 'text': type }));
			row.grab(new Element('td'));
			row.grab(locationCell);
			row.grab(new Element('td'));
			row.grab(deleteCell);
			return row;			
		},
        makeInputRow: function(){
			function blurEvent() {
				if (!this.value || !this.value.length) {
					this.value = this.title;
					this.style.color = 'gray';
				} else {
					this.style.color = 'black';
				}
			}
			
			function focusEvent() {
				if (this.value == this.title) {
					this.value = "";
					this.style.color = 'black';
					activateAutocompleter(this);
				}
			}
			
            var row = new Element('tr'), 
				inputCell = new Element('td'),
				input = new Element('input', {
	                'type': 'text',
	               	'id': 'type-input',
					'title': 'Select or enter a type...',
					'value': 'Select or enter a type...',
					'styles': {
						'color': 'gray'
					}
	            }),
				typeOptions = sharpbar.relationshipTypeOptions.sort(),
				activateAutocompleter = function(target) {
					var keyEvent = Browser.Engine.trident ? 'keydown' : 'keypress';
					target.focus();
					target.fireEvent(keyEvent, { 'key': 'down' });
				};
			
			input.addEvent('blur', blurEvent);	
			input.addEvent('focus', focusEvent);
						
			var ac = new Autocompleter.Local(input, typeOptions, {
					'overflow': true,
					'selectMode': 'selection',
					'minLength': 0
			});

			inputCell.grab(input);			
			row.grab(inputCell);
			row.grab(new Element('td').grab(new Element('input', {
				'type': 'image',
				'src': sharpbar.mediaUrl + '/Resources/images/magnify.png',
				'alt': 'List relationship types',
				'events': {
					'click': function() {
						activateAutocompleter(input);
					}
				}
			})));

            var locationCell = new Element('td'),
				locationInput = new Element('input', {
	                'type': 'text',
	                'id': 'location-input',
					'title': 'Select or enter a location...',
					'value': 'Select or enter a location...',
					'styles': {
						'color': 'gray',
						'width': '180px'
					}
	            });
				
			locationInput.addEvent('blur', blurEvent);		
			locationInput.addEvent('focus', focusEvent);
			
            locationCell.grab(locationInput);
			
			row.grab(locationCell);
			var fullUrl = sharpRegistry.activePanes && sharpRegistry.activePanes.item && sharpRegistry.activePanes.item.itemUrl ? sharpRegistry.activePanes.item.itemUrl : window.location.href;
			// TODO: Chop off any trailing badness from window.location.href
			var folderUrl = fullUrl.slice(0, fullUrl.lastIndexOf('/')+1);
            row.grab(new Element('td').grab(new CollectionBrowser(folderUrl, 'location-input')));

            row.grab(new Element('td').grab(new Element('input', {
                'type': 'button',
                'value': '+ Add',
                'id': 'relationship-add',
                'events': {
                    'click': function(){
                        var type = document.id('type-input');
                        var location = document.id('location-input');
                        if (type && type.value && type.value != 'Select or enter a type...' 
								&& location && location.value && location.value != 'Select or enter a location...') {
							if (location.value.charAt(0) != '/' && location.value.indexOf(sharpbar.applicationUrl) != 0) {
									location.value = sharpbar.applicationUrl + '/' + location.value;	
							} else if(location.value.indexOf(sharpbar.applicationUrl) != 0) {
								location.value = sharpbar.applicationUrl + location.value;
							}

                            this.add(type.value, location.value, this.relationships);
                            type.value = location.value = '';
                        }
                        else {
                            alert("Please provide a relationship type and location.");
                        }
                    }.bind(this)
                }
            })));
            return row;
        }
    });
    sharpRegistry.widgets['relationship'] = relationshipWidget;
})();
